#include<stdio.h>
#include<linux/spi/spidev.h>
#include<dirent.h>
#include<fcntl.h>
#include<string.h>
#include<sys/ioctl.h>


#define GPIO_RCK_PATH	"/sys/class/gpio/gpio117"

int spi_fd;
int RCK_fd;


int SPI1_Init( void )
{
	unsigned long mode = 0;
	unsigned long speed = 10000;
	unsigned long bits = 8;

	int fd;
	DIR *dir;

	dir = opendir( GPIO_RCK_PATH );
	if( dir == NULL )
	{
		fd = open( "/sys/class/gpio/export", O_WRONLY );
		if( fd ) 	
		{
			if( write( fd, "117", strlen( "117") ) == -1 )
			{
				close( fd );
				printf( "GPIO 3.21 export fail" );
				return -1;
			}
		}
		close( fd );
	} 	
	closedir( dir );

	fd = open( GPIO_RCK_PATH"/direction", O_WRONLY );
	write( fd, "out", strlen( "out" ) );
	close( fd );
	
	RCK_fd = open( GPIO_RCK_PATH"/value", O_RDWR ); 




	spi_fd = open( "/dev/spidev1.0", O_RDWR );
	if( spi_fd < 0 )
	{
		printf( "can not open spi device\n" );
		return -1;
	}

	if( ioctl( spi_fd, SPI_IOC_WR_MODE, &mode ) == -1 )
	{
		printf( "can not set SPI mode\n" );
		return -1;
	}

	if( ioctl( spi_fd, SPI_IOC_WR_BITS_PER_WORD, &bits ) )
	{
		printf( "can not set bits per word\n" );
	}
	if( ioctl( spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed ) == -1 )
	{
		printf( "can not set max speed HZ\n" );
		return -1;
	}

	return 0;

}


unsigned char led_table[] = 
	{ 0x89, 0x86, 0xc7, 0xc7, 0x40, 0xFF, 0xFF, 0x86, 0xc7, 0x86, 0xc6, 0x8E, 0x88, 0xc8, 0x92, 0xFF, 0xFF, 0xFF };
int main( void )
{
	unsigned char LedValueIndex = 0;
	unsigned char LedDig = 0; 
	unsigned int Times = 0;
	unsigned char tx_buffer[2];

	struct spi_ioc_transfer tx[] =
	{
		{
			.tx_buf = ( unsigned long ) tx_buffer,
			.rx_buf = 0,
			.len = 2,
			.delay_usecs = 0,
			.speed_hz = 10000,
			.bits_per_word = 8,
		},
	};

	if( SPI1_Init() == -1 )
	{
		return 0;
	}

	while( 1 )
	{

		tx_buffer[0] = led_table[LedValueIndex + LedDig];
		tx_buffer[1] = 1 << LedDig; 
		ioctl( spi_fd, SPI_IOC_MESSAGE(1), & tx ); 

		write( RCK_fd, "0", 1 );
		usleep( 100 );
		write( RCK_fd, "1", 1 );

		usleep( 1000 );

		if( ++LedDig > 3 )
			LedDig = 0;

		if( ++Times > 500 )
		{
			Times = 0;
			if( ++LedValueIndex > 14 )
				LedValueIndex = 0;
		}
		

	}

	return 0;

}




